package com.proj.android.canyondefense.core.impl;

import java.io.IOException;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

import com.proj.android.canyondefense.core.base.IMusic;

public class AndroidMusic implements IMusic, OnCompletionListener {
	private MediaPlayer _mediaPlayer;
	private boolean _isPrepared = false;
	
	public AndroidMusic(AssetFileDescriptor assetFileDescriptor) {
		_mediaPlayer = new MediaPlayer();
		try {
			_mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(), 
										assetFileDescriptor.getStartOffset(), 
										assetFileDescriptor.getLength());
			_mediaPlayer.prepare();
			_isPrepared = true;
			_mediaPlayer.setOnCompletionListener(this);
		} catch (Exception e){
			throw new RuntimeException("[AdroidMusic] :: constructor - couldn't load music!!!");
		}
	}

	public void play() {
		if (_mediaPlayer.isPlaying()) {
			return;
		}
		try {
			synchronized (this) {
				if (!_isPrepared) {
					_mediaPlayer.prepare();
				}
				_mediaPlayer.start();
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		_mediaPlayer.stop();
		synchronized (this) {
			_isPrepared = false;
		}
	}

	public void pause() {
		if (_mediaPlayer.isPlaying()) {
			_mediaPlayer.pause();
		}
	}

	public void setLooping(boolean value) {
		_mediaPlayer.setLooping(value);
	}

	public void setVolume(float value) {
		_mediaPlayer.setVolume(value, value);
	}

	public boolean isPlaying() {
		return _mediaPlayer.isPlaying();
	}

	public boolean isStopped() {
		return !_isPrepared;
	}

	public boolean isLooping() {
		return _mediaPlayer.isLooping();
	}

	public void dispose() {
		if (_mediaPlayer.isPlaying()) {
			_mediaPlayer.stop();
		}
		_mediaPlayer.release();
	}

	public void onCompletion(MediaPlayer mp) {
		synchronized (this) {
			_isPrepared = false;
		}
		
	}

}
